from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
import json

from .models import BookInfo, PeopleInfo

# Create your views here.


class BooksView(View):
    """获取所有图书、保存图书"""
    def get(self, req):
        """获取所有图书"""
        # 查询所有的图书信息
        books = BookInfo.objects.all()

        # 返回图书数据 [{},{},{}]
        book_list = list()
        for book in books:
            book_list.append(
                {
                    'id ': book.id,
                    'name': book.name,
                    'pub_date': book.pub_date,
                    'readcount': book.readcount,
                    'commentcount': book.commentcount
                }
            )

        # return http.JsonResponse(book_list, safe=True)
        return JsonResponse(book_list, safe=False)   # 源码要求，不是dict 要加safe=False

    def post(self, req):
        """保存图书"""
        # 获取数据
        json_dict = json.loads(req.body.decode())
        # 校验数据
        name = json_dict.get('name')
        pub_date = json_dict.get('pub_date')
        readcount = json_dict.get('readcount')
        commentcount = json_dict.get('commentcount')
        if not all([name, pub_date, readcount, commentcount]):
            # return http.HttpResponseForbidden('缺少参数')
            # 注意啦！前后端分离 通过json来传数据：注意格式
            return JsonResponse({'error': '缺少参数'}, status=400)
        # 省略其他验证

        # 保存到数据库
        book = BookInfo.objects.create(
            name=name,
            pub_date=pub_date,
            readcount=readcount,
            commentcount=commentcount
        )

        return JsonResponse(
            {
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date,
                'readcount': book.readcount,
                'commentcount': book.commentcount
             }
        )


class BookView(View):
    """获取单一图书、更新图书、删除图书"""
    def get(self, req, book_id):
        """获取单一图书"""
        book = BookInfo.objects.get(id=book_id)

        if not book:
            return JsonResponse({'error': '图书不存在'}, status=400)

        return JsonResponse(
            {
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date,
                'readcount': book.readcount,
                'commentcount': book.commentcount
            }
        )

    def put(self, req, book_id):
        """更新图书"""
        # 接收数据
        json_dict = json.loads(req.body.decode())
        # 校验数据
        name = json_dict.get('name')
        pub_date = json_dict.get('pub_date')
        readcount = json_dict.get('readcount')
        commentcount = json_dict.get('commentcount')
        if not all([name, pub_date, readcount, commentcount]):
            # return http.HttpResponseForbidden('缺少参数')
            # 注意啦！前后端分离 通过json来传数据：注意格式
            return JsonResponse({'error': '缺少参数'}, status=400)

        # 获取要修改的图书对象
        try:
            book = BookInfo.objects.get(id=book_id)
        except:
            return JsonResponse({'error': '信息错误'}, status=400)

        # TODO 【还不熟悉！】保存更新的数据到数据库
        book.name = name
        book.pub_date = pub_date
        book.readcount = readcount
        book.commentcount = commentcount
        book.save()

        # 返回结果
        return JsonResponse(
            {
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date,
                'readcount': book.readcount,
                'commentcount': book.commentcount
            }
        )

    def delete(self, req, book_id):
        """删除图书"""
        # 获取要删除的图书对象
        try:
            book = BookInfo.objects.get(id=book_id)
        except:
            return JsonResponse({'error': '信息错误'}, status=400)

        book.is_is_delete = True
        book.save()
        return JsonResponse({})  # 删除成功，返回空即可

        pass